<template>
  <gc-dialog
    title="批量导入"
    :dialog-visible="true"
    :loading="importLoading"
    @cancel="handleCancle"
    @ok="handleConfirm"
  >
    <el-form
      ref="formRef"
      label-position="top"
      :model="form"
      :rules="formRules"
    >
      <el-form-item label="工具分类" prop="classifyId">
        <el-select v-model="form.classifyId" placeholder="请选择">
          <el-option
            v-for="item in classifyOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="JSON文件" prop="json">
        <el-upload
          ref="upload"
          class="upload-demo"
          action="###"
          accept=".json"
          :limit="1"
          :auto-upload="false"
          @change="handleFileChange"
          @remove="handleFileRemove"
        >
          <template #trigger>
            <el-button type="primary">Select JSON File</el-button>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
  </gc-dialog>
</template>

<script setup lang="ts" name="OperateToolModal">
import { ref, reactive } from 'vue'
import { ruleRequired } from '@/utils/rules'
import type { FormInstance, FormRules, UploadFile } from 'element-plus'
import { apiGetToolClassifyList, apiBatchImportTool } from '@/http/service'
import { ElMessage } from 'element-plus'
import type { ToolClassify } from '@/http/type'
import { isArray } from '@/utils'

interface Form {
  classifyId: number | null
  json: UploadFile | null
}
const emit = defineEmits(['close-modal'])
const importLoading = ref(false)
const classifyOptions = ref<Array<ToolClassify>>()
const formRef = ref<null | FormInstance>(null)
const form = reactive<Form>({
  classifyId: null,
  json: null
})

const formRules = reactive<FormRules>({
  classifyId: [ruleRequired('请选择工具分类')],
  json: [ruleRequired('请上传需要批量上传的JSON文件')]
})

async function getToolClassifyList () {
  const data = await apiGetToolClassifyList<Array<ToolClassify>>()
  classifyOptions.value = data
}
getToolClassifyList()

async function handleConfirm () {
  const valid = await formRef.value?.validate()
  if (valid) {
    importLoading.value = true
    try {
      const { successTotal, failTotal } = await apiBatchImportTool(form) as any
      emit('close-modal', true)
      ElMessage.success(`批量导入工具成功${successTotal}个，失败${failTotal}个`)
    } catch (e) {} finally {
      importLoading.value = false
    }
  }
}

async function handleFileChange (uploadFile: UploadFile) {
  const data: any = await readFileContent(uploadFile.raw)
  try {
    const listJson = JSON.parse(data)
    if (!isArray(listJson)) {
      return ElMessage.error('批量导入只支持Array格式的json')
    }
    form.json = listJson
  } catch (error) {
    ElMessage.error('JSON文件异常')
  }
}

function readFileContent (file: any) {
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.onload = (e: any) => {
      resolve(e.target.result)
    }
    reader.readAsText(file)
  })
}

function handleFileRemove () {
  form.json = null
}

function handleCancle () {
  emit('close-modal')
}
</script>

<style scoped lang="scss"></style>
